const express = require('express');
const { body, param, query } = require('express-validator');
const CheckupController = require('../controllers/checkup.controller');
const router = express.Router();

// 验证规则
const createCheckupValidation = [
  body('healthExamination.da_id')
    .notEmpty()
    .withMessage('档案ID不能为空'),
  body('healthExamination.xm')
    .notEmpty()
    .withMessage('姓名不能为空')
    .isLength({ min: 2, max: 50 })
    .withMessage('姓名长度应在2-50个字符之间'),
  body('healthExamination.sfzh')
    .optional({ nullable: true, checkFalsy: true })
    .isLength({ min: 15, max: 18 })
    .withMessage('身份证号长度不正确'),
  body('healthExamination.tjrq')
    .notEmpty()
    .withMessage('体检日期不能为空')
    .isISO8601()
    .withMessage('体检日期格式不正确')
];

const updateCheckupValidation = [
  param('id')
    .isInt({ min: 1 })
    .withMessage('体检记录ID必须是正整数'),
  body('healthExamination.xm')
    .optional()
    .isLength({ min: 2, max: 50 })
    .withMessage('姓名长度应在2-50个字符之间'),
  body('healthExamination.sfzh')
    .optional()
    .isLength({ min: 15, max: 18 })
    .withMessage('身份证号长度不正确')
];

const idValidation = [
  param('id')
    .isInt({ min: 1 })
    .withMessage('ID必须是正整数')
];

const listValidation = [
  query('page')
    .optional()
    .isInt({ min: 1 })
    .withMessage('页码必须是正整数'),
  query('limit')
    .optional()
    .isInt({ min: 1, max: 100 })
    .withMessage('每页数量必须在1-100之间'),
  query('startDate')
    .optional()
    .isISO8601()
    .withMessage('开始日期格式不正确'),
  query('endDate')
    .optional()
    .isISO8601()
    .withMessage('结束日期格式不正确')
];

// 路由定义

/**
 * @route POST /api/checkups
 * @desc 创建体检记录
 * @access Private
 */
router.post('/', createCheckupValidation, CheckupController.createCheckup);

/**
 * @route GET /api/checkups
 * @desc 获取体检记录列表
 * @access Private
 */
router.get('/', listValidation, CheckupController.getCheckupList);

/**
 * @route GET /api/checkups/stats
 * @desc 获取体检统计信息
 * @access Private
 */
router.get('/stats', CheckupController.getCheckupStats);

/**
 * @route GET /api/checkups/:id
 * @desc 获取体检记录详情
 * @access Private
 */
router.get('/:id', idValidation, CheckupController.getCheckup);

/**
 * @route PUT /api/checkups/:id
 * @desc 更新体检记录
 * @access Private
 */
router.put('/:id', updateCheckupValidation, CheckupController.updateCheckup);

/**
 * @route DELETE /api/checkups/:id
 * @desc 删除体检记录
 * @access Private
 */
router.delete('/:id', idValidation, CheckupController.deleteCheckup);

/**
 * @route GET /api/checkups/archive/:daId
 * @desc 根据档案ID获取体检记录
 * @access Private
 */
router.get('/archive/:daId', [
  param('daId')
    .notEmpty()
    .withMessage('档案ID不能为空')
], CheckupController.getCheckupByDaId);

/**
 * @route DELETE /api/checkups/batch
 * @desc 批量删除体检记录
 * @access Private
 */
router.delete('/batch', [
  body('ids')
    .isArray({ min: 1 })
    .withMessage('请提供要删除的ID数组'),
  body('ids.*')
    .isInt({ min: 1 })
    .withMessage('ID必须是正整数')
], CheckupController.batchDeleteCheckups);

module.exports = router;